package com.healthlink.appcloudcalllib;

import static com.healthlink.appcloudcalllib.common.ClickUtils.lastClickTime;
import static com.healthlink.appcloudcalllib.common.MessageType.MISSMQ;
import static com.healthlink.appcloudcalllib.common.MessageType.CALL_HANG_UP;
import static com.healthlink.appcloudcalllib.common.MessageType.CALL_LOG;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.healthlink.appcloudcalllib.callback.ICallMessage;
import com.healthlink.appcloudcalllib.callback.ICallInCallback;
import com.healthlink.appcloudcalllib.callback.IGoonCallback;
import com.healthlink.appcloudcalllib.callback.IInitCallBack;
import com.healthlink.appcloudcalllib.callback.ICallOutCallback;
import com.healthlink.appcloudcalllib.callback.IResultCallback;
import com.healthlink.appcloudcalllib.callback.MessageCallBack;
import com.healthlink.appcloudcalllib.common.ClickUtils;
import com.healthlink.appcloudcalllib.common.Constants;
import com.healthlink.appcloudcalllib.common.MessageType;
import com.healthlink.appcloudcalllib.keeplive.KeepLiveMqttService;
import com.healthlink.appcloudcalllib.utils.CallUtils;
import com.healthlink.appcloudcalllib.utils.CommonUtil;
import com.healthlink.appcloudcalllib.utils.Out;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * 云呼叫
 * 2022-12-05
 * wangying
 */
public class CloudCallManager {

    private Handler handler;
    private Context mContext;
    private CallUtils agoraUtils;
    private IInitCallBack iInitCallBack;
    public MessageCallBack iMessageCallBack;
    public static volatile CloudCallManager cloudCallManager;



    private CloudCallManager() {
    }

    public static CloudCallManager getInstance() {
        if (cloudCallManager == null) {
            synchronized (CloudCallManager.class) {
                if (cloudCallManager == null) {
                    cloudCallManager = new CloudCallManager();
                }
            }
        }
        return cloudCallManager;
    }
    /**
     * 设置SDK消息监听
     * @param iMessageCallBack
     */
    public void setMessageListener(MessageCallBack iMessageCallBack){

        this.iMessageCallBack=iMessageCallBack;
    }

    public List<String> getLogs(){
        return Constants.logs;
    }
    /**
     * 初始化SDK
     * @param context
     */
    public void init(Context context, String asToken, String appId,String productId, IInitCallBack iInitCallBack) {
        mContext = context;


        try {
            Constants.logs.clear();
        }catch (Exception e){

        }
        Constants.logs.add("开始初始化："+System.currentTimeMillis());
        handler=new Handler();
        this.asToken=asToken;
        this.pid=productId;
        this.apId=appId;
        this.iInitCallBack=iInitCallBack;
        CommonUtil.checkSelfPermission(context);
        Constants.logs.add("声网开始初始化："+System.currentTimeMillis());
        CallUtils.getInstance().init(context,agoraMessageCallback);
        Constants.logs.add("声网初始化成功："+System.currentTimeMillis());
        final String serialnoStr = "[ro.boot.serialno]";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Process p = Runtime.getRuntime().exec("getprop");
                    p.waitFor();
                    BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                            p.getInputStream()));
                    String temp = "";
                    while ((temp = stdInput.readLine()) != null) {
                        if (temp.contains(serialnoStr)) {
                            temp.replaceAll(" ", "");
                            int index = temp.indexOf(serialnoStr);
                            temp = temp.substring(index + 20);
                            temp = temp.substring(1, temp.length() - 1);

                            if (!TextUtils.isEmpty(temp)){
                                Constants.sn=temp;

                            }else{
                                Constants.sn=Out.getAndroidId(mContext);

                            }

                            break;
                        }
                    }
                    if (TextUtils.isEmpty(temp)){

                        Constants.sn=Out.getAndroidId(mContext);

                    }
                } catch (Exception exception){
                    exception.printStackTrace();
                    Constants.sn=Out.getAndroidId(mContext);
                }
                try {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Constants.logs.add("初始化（获取未完成通话）："+System.currentTimeMillis());
                            CallUtils.getInstance().getLastCall(asToken, appId, productId, new IInitCallBack() {
                                @Override
                                public void initResult(int code, String data) {

                                    Constants.logs.add("初始化（未完成通话返回）："+System.currentTimeMillis());
                                    iInitCallBack.initResult(code,data);

                                        doMqtt(context,0);


                                }
                            });
                        }
                    });

                }catch (Exception exception){exception.printStackTrace();
                Out.out2("eeeee"+exception.getMessage());
                }
            }

        }).start();
    }
  public boolean isAlive(Context context){
        return isServiceRunning(context,KeepLiveMqttService.class.getName());
  }
    /**
     * 判断服务是否正在运行
     *
     * @param context
     * @param className 判断的服务名字：包名+类名
     * @return true在运行 false 不在运行
     */
    public static boolean isServiceRunning(Context context, String className) {
        boolean isRunning = false;
        try {
            ActivityManager activityManager = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            //获取所有的服务
            List<ActivityManager.RunningServiceInfo> services= activityManager.getRunningServices(Integer.MAX_VALUE);
            if(services!=null&&services.size()>0){
                for(ActivityManager.RunningServiceInfo service : services){
                    if(className.equals(service.service.getClassName())){
                        isRunning=true;
                        break;
                    }
                }
            }
        }catch (Exception e){}

        return isRunning;
    }
    private ICallMessage agoraMessageCallback= new ICallMessage() {

        @Override
        public void initSuccess() {

        }

        @Override
        public void onUserjoin(int uid) {

        }

        @Override
        public void onUserOffline() {


        }
    };



    Intent intentService;
    private String apId;
    private String asToken;
    private String pid;
    private ICallOutCallback iCallOutCallback2;
    /**
     * 拨号
     * @param iCallOutCallback
     */
    public void requestCallOut(Context context,String accessToken,String appId,String productId,ICallOutCallback iCallOutCallback){

//        iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"SDK开始响应");
        if (ClickUtils.isFastClick()){

            Out.out("开始拨号");
            this.apId=appId;
            this.asToken=accessToken;
            this.pid=productId;
            this.iCallOutCallback2=iCallOutCallback;
//            iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"获取mq配置");
            Out.lastMqTime=0;
            Constants.logs.add("开始拨号:"+System.currentTimeMillis());
             doMqtt(context,1);
        }else {
            Out.out2("快速请求");
        }


    }
    int mqttype=0;

    private void doMqtt(Context context,int type) {
        mqttype=type;
        if (Out.isFastMqOk()){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (intentService!=null){
                            try {
                                context.stopService(intentService);
                                intentService=null;
                            }catch (Exception exception){
                                exception.printStackTrace();
                            }
                        }
                        intentService=new Intent(context,KeepLiveMqttService.class);
                        intentService.putExtra("appId",apId);
                        intentService.putExtra("host",Constants.HOST);
                        intentService.putExtra("astoken",asToken);
                        intentService.putExtra("sn",Constants.sn);
                        intentService.putExtra("type",type);
                        context.startService(intentService);
                        Constants.logs.add("初始化（启动mq）："+System.currentTimeMillis());

//                        iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"启动keeplive服务..");
                    }catch (Exception exception){
//                        iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"mq错误："+exception.getMessage());
                        exception.printStackTrace();
                    }

                }
            });
        }else{
//            iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"mq请求过多");
            Out.out2("mq请求过多");
        }


    }

    private String callintoken;
    private String callinrooid;
    private Context callincontext;
    private String callincaller;
    private String callincallee;
    private ICallInCallback callinICallInCallback;
    /**
     * 接通来电
     * @param accessToken
     * @param iCallInCallback
     */
    public void acceptCallIn(Context contlext,String accessToken,String roomId,String caller,String callee,ICallInCallback iCallInCallback){

        Out.out2("同意接通AAA");
        if (ClickUtils.isFastClick()){

            Out.out2("同意接通BBB");
            this.callincontext=contlext;
            this.callinrooid=roomId;
            this.callincallee=callee;
            this.callincaller=caller;
            this.callintoken=accessToken;
            this.callinICallInCallback=iCallInCallback;
            Intent intent = new Intent();
            intent.putExtra("msg","acceptcallin@");
            intent.putExtra("token",accessToken);
            intent.setAction("com.bjym.callmethod");
            contlext.sendBroadcast(intent);
//
        }
        }

    int flagshow=0;
    /**
     * 拒绝接通
     * @param accessToken
     * @param roomId
     * @param iResultCallback
     */
    public void refuseCallIn(Context context,String accessToken,String roomId,IResultCallback iResultCallback){
        if (ClickUtils.isFastClick()){
            flagshow=1;
            flagshowmeet=0;
            CallUtils.getInstance().hangUp(context, accessToken, roomId, 0, new IResultCallback() {
                @Override
                public void onCallback(int state) {
                    if (state==203){
                        lastClickTime=0;
                        Out.out2("重置时间AA");
                    }
                    iResultCallback.onCallback(state);
                    if (state==0){
                        Intent intent = new Intent();
                        intent.putExtra("msg","guaduan@");
                        intent.putExtra("token",accessToken);
                        intent.setAction("com.bjym.callmethod");
                        context.sendBroadcast(intent);
                    }

                }
            });

        }

    }

    /**
     *挂断电话
     * @param accessToken
     * @param roomId
     * @param iResultCallback
     */
    public void hangupCall(Context context, String accessToken, String roomId, IResultCallback iResultCallback){

        Out.out2("挂断AAA");
      if (ClickUtils.isFastClick()){
          Out.out2("挂断BBB");
          flagshow=1;
          flagshowmeet=0;
          CallUtils.getInstance().hangUp(context, accessToken, roomId, 1, new IResultCallback() {
              @Override
              public void onCallback(int state) {
                  if (state==203){
                      lastClickTime=0;
                  }
                  iResultCallback.onCallback(state);
                  if (state==0){
                      Intent intent = new Intent();
                      intent.putExtra("msg","guaduan@");
                      intent.putExtra("token",accessToken);
                      intent.setAction("com.bjym.callmethod");
                      context.sendBroadcast(intent);
                  }

              }
          });

      }
    }

    /**
     * 设置测试模式
     * @param isDebug
     */
    public void setDebug(boolean isDebug){
//        if (isDebug){
//            Constants.HOST="https://saptest-micro.healthlink.cn/api/";
//        }else{
//            Constants.HOST="https://saptest-micro.healthlink.cn/api/";
//        }


    }
    /**
     * 设置url
     * @param url
     */
    public void setHost(String url){
            Constants.HOST=url;

    }

    /**
     * 设置静音
     * @param ismute true 静音 , false 取消静音
     */
    public void setMute(boolean ismute){
        CallUtils.getInstance().mute(ismute);

    }

    public void setVolume(int volume){
        try {
            CallUtils.getInstance().setVolume(volume);
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
    public void setLogs(boolean isShow){
        CommonUtil.showLog=isShow;
    }
    int flagshowmeet=0;
    public void onServiceCallBack(int state, String message){
        if (state==1){
            Out.out("请求拨号1");
//            iMessageCallBack.onGetMessage(MessageType.CALL_LOG,"mq连接成功开始请求拨号");
            flagshow=0;
            Constants.logs.add("正式请求拨号："+System.currentTimeMillis());
            CallUtils.getInstance().careateRoom(asToken,apId,pid, iCallOutCallback2);
        }
       else if (state==777){
            iMessageCallBack.onGetMessage(MISSMQ,"");
        }
        else if (state==2){
            flagshow=0;
            CallUtils.getInstance().joinTORoom(callincontext,callintoken,callinrooid,callincaller,callincallee,callinICallInCallback);

        }
        else if (state==4){
            flagshow=0;
            lastClickTime=0;
            Out.out2("重置时间BBB");
            callinICallInCallback.onCallInState(203);

        }
        else if (state==203){
            lastClickTime=0;
            if (mqttype==0){
                try {
                    iInitCallBack.initResult(203,"");
                }catch (Exception e){}
            }

            iCallOutCallback2.onCallingCreate(203,"");
        }
        else if (state==888){
            try {
                JSONObject dataObj= JSONObject.parseObject(message);
                String event=dataObj.getString("event");
                switch (event){
                    case "enterMeet":
                            if (flagshowmeet==0){
                                iMessageCallBack.onGetMessage(MessageType.CALL_IN,message);
                                flagshowmeet=1;
                                flagshow=0;
                            }
                        break;
                    case "sipConnect":
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    iMessageCallBack.onGetMessage(MessageType.CALL_CONECTED,message);
                                }
                            },500);

                        break;
                    case "sipHangUp":
//                            CallUtils.getInstance().levalChanel();
                           flagshowmeet=0;
                            if (flagshow==0){
                                Intent intent = new Intent();
                                intent.putExtra("msg","guaduan@");
                                intent.putExtra("token",asToken);
                                intent.setAction("com.bjym.callmethod");
                                mContext.sendBroadcast(intent);
                                iMessageCallBack.onGetMessage(CALL_HANG_UP,message);
                            }else{
                                flagshow=0;
                            }
                        break;
                    default:
                        break;
                }

            }catch (Exception exception){
                Out.out2("处理消息消息error："+message+"==="+exception.getMessage());
            }



        }
        else{
            try {

                Out.out("拨号回调else："+state+"=="+message);
            }catch (Exception e){}
            iCallOutCallback2.onCallingCreate(state,"");
        }
    }

    /**
     * 继续上次通话
     * @param context
     * @param token
     * @param roomId
     * @param uid
     * @param iGoonCallback
     */
    public void goonLastCall(Context context, String token, String roomId, String uid, IGoonCallback iGoonCallback){
        if (ClickUtils.isFastClick()){
            Constants.logs.add("开始加入上次通话:"+System.currentTimeMillis());
            CallUtils.getInstance().goonLastCall(token,roomId,uid,iGoonCallback);
        }
    }

    /**
     * 停止调用
     * @param context

     */
    public void recycleCall(Context context){
        if (ClickUtils.isFastClick()){

            try {
                context.stopService(intentService);
            }catch (Exception e){

            }


        }
    }
}
